--请注意！！
--使用本开源需要在开源引用页面中加入本仓库地址.
--https://gitee.com/luo-ying2020/GIT_update
--©Copyright by 洛樱

--Please pay attention! ! 
--to use this open source, you need to add the address of this warehouse to the open source reference page.
--https://gitee.com/luo-ying2020/GIT_update
--©copyright by Luo Ying


require "import"
import "android.app.*"
import "android.support.v7.widget.*"
import "android.support.design.widget.*"
import "android.support.v4.widget.*"
import "android.widget.*"
import "layout"
import "android.view.View"
import "java.io.File"


import"init"--读取本地版本信息
local 请求={}
请求.Git作者="ccimage"
请求.Git仓库="PasswordKeeper"
请求.本地版本号=appver
请求.国内=true

--https://gitee.com/ccimage/PasswordKeeper/releases/v1.0
--https://gitee.com/api/v5/repos/{owner}/{repo}/releases/latest


--状态栏
import "android.view.WindowManager"
activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)

--布局文件
updatelay={
  LinearLayout;
  orientation="vertical";
  gravity="center";
  layout_width="fill";
  layout_height="fill";
  background="#FFFEF3E7";
  {
    LinearLayout;
    orientation="vertical";
    layout_width="60%w";
    gravity="center";
    layout_height="60%w";
    {
      ImageView;
      layout_margin="30dp";
      layout_width="65dp";
      layout_height="65dp";
      src="icon.png";
    };
    {
      LinearLayout;
      orientation="vertical";
      gravity="center";
      layout_width="fill";
      layout_height="30dp";
      id="update";
      {
        LinearLayout;
        orientation="horizontal";
        layout_weight="1";
        layout_width="fill";
        layout_height="60dp";
        {
          ProgressBar;
          indeterminate=true;
          layout_weight="1";
          layout_height="30dp";
          style="?android:attr/progressBarStyleHorizontal";
          progress=0;
          max=100;
          id="progress";
          layout_width="fill";
          padding="25";
          layout_marginLeft="30dp";
        };
        {
          TextView;
          id="speed1";
          layout_height="fill";
          gravity="center";
          layout_width="40dp";
          text="0%";
          textSize="12sp";
          textColor="#FF272624";
        };
      };
    };
    {
      TextView;
      text="正在启动更新检查...";
      id="text_update";
      textColor="#FF272624";
      textSize="16sp";
    };
  };
};


activity.setTitle('检查更新')
--activity.ActionBar.hide()
--activity.setTheme(R.style.NoActionBarLightTheme)
activity.setContentView(loadlayout(updatelay))
--运行函数
function 粗化文本控件(ID)
  if pcall(function()
      import "android.graphics.Paint"
      ID.getPaint().setFakeBoldText(true)
    end) then
   else
    print"字体粗化设置出错"
  end
end


local function 检查完毕(tex)
  text_update.setText(tex)
  update.setVisibility(View.GONE)--隐藏条
  task(1500,function()
    activity.finish()
  end)
end

local function 检查中(tex)
  text_update.setText(tex)
end

function Download(url,path,func)
  --文件传输可视化
  function setProgress(c,t)
    local max = c / t * 100
    switch max
     case 100
      -- title.setText("下载完成")
      progress.progress = max
      speed1.setText(("%d%%"):format(max))
      -- speed2.setText(("%d/100"):format(max))
     default
      progress.progress = max
      speed1.setText(("%.2f%%"):format(max))
      --speed2.setText(("%.2f/100"):format(max))
    end
  end

  --下载文件
  local function getFile(url,path,func)

    require"import"
    import"java.io.File"
    import"java.net.URL"
    import"java.io.FileOutputStream"
    --建造目录
    local paths=activity.getLuaDir() .. "/update/"
    File(paths).mkdirs()


    local url = URL(url)
    local file = File(path)
    local con = url.openConnection()
    local co = con.getContentLength()
    local is = con.getInputStream()
    local bs= byte[1024]
    local len = 0
    local read = 0
    local wj = FileOutputStream(path)
    len = is.read(bs)
    while len ~= -1
      wj.write(bs,0,len)
      read = read + len
      pcall(call,"setProgress",read,co)
      len = is.read(bs)
    end
    wj.close()
    is.close()
    if len == -1
      --print("下载成功")
      --  检查完毕("正在安装更新...")
      if func
        func()
      end
     else
      task(1500,function()
        print("下载失败")
        activity.finish()
      end)
      --print("下载失败")
    end
  end
  --弹起对话框执行
  --  dialog = AlertDialog.Builder(activity)
  --  .setView(loadlayout(layout))
  --  .show()
  --  .setCancelable(false)
  thread(getFile,url,path,func)
end

function 文件后缀(文件名)
  return 文件名:match(".+%.(%w+)$")
end

function 是否文件(path)
  return File(tostring(path)).isFile()
end

local function 路径清除(path)
  File(path).mkdirs()
  os.execute("rm -r "..path)
  --print(path)
end


function APPupdate(url,name)
  local url = url
  local paths=activity.getLuaDir() .. "/update/"
  File(paths).mkdirs()
  local path = paths..name
  local function Installplug(path)
    import "android.webkit.MimeTypeMap"
    import "android.content.Intent"
    import "android.net.Uri"
    import "java.io.File"
    FileName=tostring(File(path).Name)
    ExtensionName=FileName:match(".+%.(%w+)$")
    Mime=MimeTypeMap.getSingleton().getMimeTypeFromExtension(ExtensionName)
    if Mime then
      intent = Intent();
      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      intent.setAction(Intent.ACTION_VIEW);
      intent.setDataAndType(Uri.fromFile(File(path)), Mime);
      activity.startActivity(intent);
     else
      print("找不到可以用来打开此文件的程序")
    end
  end
  if 是否文件(path) then
    检查完毕("检测到本地更新")
    task(500,function()
    Installplug(path)
    end)
   else
    路径清除(activity.getLuaDir().."/update/")
    检查中("正在获取数据..")
    Download(url,path,function()--回调
      require "import"
      Installplug(path)
      task(500,function()
        activity.finish()
      end)
    end)
  end

end

import "android.graphics.PorterDuff"
import "android.graphics.PorterDuffColorFilter"
progress.IndeterminateDrawable.setColorFilter(PorterDuffColorFilter(0xFFFB7299,PorterDuff.Mode.SRC_ATOP))



粗化文本控件(text_update)
--APPupdate(url,os.date("%H").."."..文件后缀(url))

function 检查更新()
  -- 检查中("网络错误"..tostring(code))
  if 请求.国内==true then
    url="https://gitee.com/api/v5/repos/"..请求.Git作者.."/"..请求.Git仓库.."/releases/latest"
    else
    url="https://api.github.com/repos/"..请求.Git作者.."/"..请求.Git仓库.."/releases/latest"
    end
  Http.get(url,nil,"UTF-8",nil,function(code,content,cookie,header)
    import "json"
    if code==200 then
      local content=json.decode(content)
      if content.tag_name~=请求.本地版本号 then
        url=content.assets[1].browser_download_url
        --print(url)
        if 请求.国内==true then
        APPupdate(url,tostring(content.assets[1].name))
        else
        APPupdate(url,tostring(content.tag_name).."."..文件后缀(url))
        end
       else
        检查完毕("已经是最新版本")
      end
     else
      检查完毕("网络错误"..tostring(code))
    end
  end)
end


task(300,function()
  检查更新()
end)